# -*- coding: utf-8 -*-
# @Time : 2021/6/7 上午9:26
# @Author : fugang_le

# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# @Time : 2021/6/4 下午5:11
# @Author : fugang_le
import re
from elasticsearch import Elasticsearch
import sys
sys.path.append('/data/lefugang/template1/predict/template1')
from configs.config import ES_HOST


SPLIT_PATTERN = re.compile(r'[,，]')


class ES_Util():
    es_client = Elasticsearch(hosts=ES_HOST)
    # index = ES_INDEX

    @classmethod
    def search_CMS(cls, index, classification, materialName, sepc, size=10):
        body = {
            "query":
                {
                    "bool":{
                        "must": [
                            {
                                "term": {
                                    "classification.keyword": classification,
                                }
                            },
                            {
                                "match": {
                                    "materialName": materialName,
                                }
                            },
                            {
                                "multi_match": {
                                    'query':sepc,
                                    "fields": ['materialName', 'sepc']
                                }
                            },
                        ]
                    }
                }
        }
        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_CM(cls, index, classification, materialName, size=10):
        body = {
            "query":
                {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "classification.keyword": classification,
                                },
                            },
                            {
                                "match": {
                                    'materialName': materialName,
                                }
                            },
                        ]
                    }
                }
        }

        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_material_name_sepc(cls, index, classification, text, size=10):
        body = {
            "query":
                {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "classification.keyword": classification,
                                },
                            },
                            {
                                "match": {
                                    'material_name_sepc': text,
                                }
                            },
                        ]
                    }
                }
        }

        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_classification(cls, index, classification, size=10):
        body = {
            'query':{
                'term':{
                    "classification.keyword": classification,
                }
            }
        }

        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_secoArea(cls, index, text, classification, secoArea, size=10):
        body = {
            "query":
                {
                    "bool": {
                        "must": [
                            { "term": {"classification.keyword": classification, }},
                            { "term": {"secoArea.keyword": secoArea}},
                            { "match":{'materialName': text,}},
                        ]
                    }
                }
        }

        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_price_condition(cls, index, text, classification, grid_type, price_conditions, size=10):
        def func(price_condition_dict):
            price_condition_list = []
            if price_condition_dict['fir_area']:
                price_condition_list.append({'term': {'firArea.keyword': price_condition_dict['fir_area']}})
            if price_condition_dict['seco_area']:
                # 存在多个条件，用逗号切分
                seco_areas = SPLIT_PATTERN.split(price_condition_dict['seco_area'].strip())
                shoulds = []
                for seco_area in seco_areas:
                    if seco_area:
                        shoulds.append({'term': {'secoArea.keyword': seco_area}})
                price_condition_list.append({'bool':{'should':shoulds}})
            if price_condition_dict['third_area']:
                price_condition_list.append({'term': {'thirdArea.keyword': price_condition_dict['third_area']}})
            if price_condition_dict['particular_year']:
                price_condition_list.append({'term': {'particularYear.keyword': price_condition_dict['particular_year']}})
            if price_condition_dict['time_version']:
                # 存在多个条件，用逗号切分
                time_versions = SPLIT_PATTERN.split(price_condition_dict['time_version'].strip())
                shoulds = []
                for time_version in time_versions:
                    if time_version:
                        shoulds.append({'term': {'timeVersion.keyword': time_version}})
                price_condition_list.append({'bool':{'should':shoulds}})
            # if price_condition_dict['time_version']:
            #     price_condition_list.append({'term': {'timeVersion.keyword': price_condition_dict['time_version']}})
            return price_condition_list

        body = {
            'query':
                {'bool': {
                    'must': [
                        {
                            'bool': {
                                'should': []}
                        },
                        {'match': {'materialNameSepc': text}},
                    ]
                }
            }
        }

        if grid_type in ['主网', '配网']:
            body['query']['bool']['must'].append(
                {'bool':{
                    'should': [
                            {'term':{'gridType.keyword': grid_type}}, 
                            {"bool": {"must_not": [{"wildcard": {"gridType": {"value": "*"}}}]}}
                        ]
                    }
                },
            )
        elif grid_type == '全部':
            body['query']['bool']['must'].append(
                {'bool':{
                    'should': [
                            {'term':{'gridType.keyword': '主网'}}, 
                            {'term':{'gridType.keyword': '配网'}}, 
                            {"bool": {"must_not": [{"wildcard": {"gridType": {"value": "*"}}}]}},
                        ]
                    }
                }
            )

        price_condition_one = price_conditions['price_condition_one']
        price_condition_two = price_conditions['price_condition_two']
        price_condition_three = price_conditions['price_condition_three']

        price_condition_one_must = func(price_condition_one)
        price_condition_two_must = func(price_condition_two)
        price_condition_three_must = func(price_condition_three)

        should_query = []
        if price_condition_one_must:
            should_query.append({'bool':{'must':price_condition_one_must}})
        if price_condition_two_must:
            should_query.append({'bool':{'must':price_condition_two_must}})
        if price_condition_three_must:
            should_query.append({'bool':{'must':price_condition_three_must}})

        if classification:
            body['query']['bool']['must'].append({'term': {'classification.keyword': classification}})
        body['query']['bool']['must'][0]['bool']['should'] = should_query
        # print(body)
        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']

    @classmethod
    def search_price_condition_by_wildcard(cls, index, text, classification, grid_type, price_conditions, size=10):
        def func(price_condition_dict):
            price_condition_list = []
            if price_condition_dict['fir_area']:
                price_condition_list.append({'term': {'firArea.keyword': price_condition_dict['fir_area']}})
            if price_condition_dict['seco_area']:
                # 存在多个条件，用逗号切分
                seco_areas = SPLIT_PATTERN.split(price_condition_dict['seco_area'].strip())
                shoulds = []
                for seco_area in seco_areas:
                    if seco_area:
                        shoulds.append({'term': {'secoArea.keyword': seco_area}})
                price_condition_list.append({'bool':{'should':shoulds}})
            if price_condition_dict['third_area']:
                price_condition_list.append({'term': {'thirdArea.keyword': price_condition_dict['third_area']}})
            if price_condition_dict['particular_year']:
                price_condition_list.append({'term': {'particularYear.keyword': price_condition_dict['particular_year']}})
            if price_condition_dict['time_version']:
                # 存在多个条件，用逗号切分
                time_versions = SPLIT_PATTERN.split(price_condition_dict['time_version'].strip())
                shoulds = []
                for time_version in time_versions:
                    if time_version:
                        shoulds.append({'term': {'timeVersion.keyword': time_version}})
                price_condition_list.append({'bool':{'should':shoulds}})
            # if price_condition_dict['time_version']:
            #     price_condition_list.append({'term': {'timeVersion.keyword': price_condition_dict['time_version']}})
            return price_condition_list

        body = {
            'query':
                {'bool': {
                    'must': [
                        {
                            'bool': {
                                'should': []}
                        },
                        {'wildcard': {'materialNameSepc': "*" + text + "*"}},
                    ]
                }
            }
        }

        if grid_type in ['主网', '配网']:
            body['query']['bool']['must'].append(
                {'bool':{
                    'should': [
                            {'term':{'gridType.keyword': grid_type}}, 
                            {"bool": {"must_not": [{"wildcard": {"gridType": {"value": "*"}}}]}}
                        ]
                    }
                },
            )
        elif grid_type == '全部':
            body['query']['bool']['must'].append(
                {'bool':{
                    'should': [
                            {'term':{'gridType.keyword': '主网'}}, 
                            {'term':{'gridType.keyword': '配网'}}, 
                            {"bool": {"must_not": [{"wildcard": {"gridType": {"value": "*"}}}]}},
                        ]
                    }
                }
            )

        price_condition_one = price_conditions['price_condition_one']
        price_condition_two = price_conditions['price_condition_two']
        price_condition_three = price_conditions['price_condition_three']

        price_condition_one_must = func(price_condition_one)
        price_condition_two_must = func(price_condition_two)
        price_condition_three_must = func(price_condition_three)

        should_query = []
        if price_condition_one_must:
            should_query.append({'bool':{'must':price_condition_one_must}})
        if price_condition_two_must:
            should_query.append({'bool':{'must':price_condition_two_must}})
        if price_condition_three_must:
            should_query.append({'bool':{'must':price_condition_three_must}})

        if classification:
            body['query']['bool']['must'].append({'term': {'classification.keyword': classification}})
        body['query']['bool']['must'][0]['bool']['should'] = should_query
        # print(body)
        result = cls.es_client.search(index=index, body=body, size=size)
        return result['hits']['hits']



if __name__ == '__main__':
    es = ES_Util()

    price_conditions = {
        'price_condition_one': {'fir_area': '国网', 'seco_area': '总部,福建', 'third_area': '', 'particular_year': '2021',
                                'time_version': '二季度'},
        'price_condition_two': {'fir_area': '国网', 'seco_area': '总部,福建', 'third_area': '', 'particular_year': '2020',
                                'time_version': '一季度'},
        'price_condition_three': {'fir_area': '', 'seco_area': '', 'third_area': '', 'particular_year': '',
                                  'time_version': ''},

    }

    price_conditions = {
        "price_condition_one": {"fir_area": "北京市", "particular_year": "2021", "seco_area": "北京市", "third_area": "",
                                "time_version": "8"},
        "price_condition_three": {"fir_area": "", "particular_year": "", "seco_area": "", "third_area": "",
                                "time_version": ""},
        "price_condition_two": {"fir_area": "", "particular_year": "", "seco_area": "", "third_area": "",
                                "time_version": ""}
                                }

    # result = es.search_material_name_sepc('czw-library-test', "消防器材", '5')
    # result = es.search_CM('czw-library-test', "消防器材", "短切毡")
    # result = es.search_classification('czw-library-test', "", size=100)
    # result = es.search_secoArea('material-library-test2', '钢绞线', '导线', '广东', size=10)
    result = es.search_price_condition('material-library-187', '平焊法兰 pn1.6 dn100', '', '全部', price_conditions, size=10)
    # print(result)
    for items in result:
        print(items)
        print()

